<html lang="en-US">

<head>
    
<title>「连载八」为它加上Swagger - 花落雨忧</title>

<meta property="og:title" content="「连载八」为它加上Swagger - 花落雨忧">



    



    
    <meta property="description" content="一个好的 API&#39;s，必然离不开一个好的API文档，如果要开发纯手写 API 文档，不存在的（很难持续维护），因此我们要自动生成接口文档。
[&amp;hellip;] $ go get -u github.com/swaggo/swag/cmd/swag@v1.6.5 若 $GOROOT/bin 没有加入$PATH中，你需要执行将其可执行文件移动到$GOBIN下
mv $GOPATH/bin/swag &amp;hellip;">
    <meta property="og:description" content="一个好的 API&#39;s，必然离不开一个好的API文档，如果要开发纯手写 API 文档，不存在的（很难持续维护），因此我们要自动生成接口文档。
[&amp;hellip;] $ go get -u github.com/swaggo/swag/cmd/swag@v1.6.5 若 $GOROOT/bin 没有加入$PATH中，你需要执行将其可执行文件移动到$GOBIN下
mv $GOPATH/bin/swag &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/gin/2018-03-18-swagger/">「连载八」为它加上Swagger</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/03/18</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="涉及知识点">涉及知识点</h2>
<ul>
<li>Swagger</li>
</ul>
<h2 id="本文目标">本文目标</h2>
<p>一个好的 <code>API's</code>，必然离不开一个好的<code>API</code>文档，如果要开发纯手写 <code>API</code> 文档，不存在的（很难持续维护），因此我们要自动生成接口文档。</p>
<h2 id="安装-swag">安装 swag</h2>
<pre tabindex="0"><code>$ go get -u github.com/swaggo/swag/cmd/swag@v1.6.5
</code></pre><p>若 <code>$GOROOT/bin</code> 没有加入<code>$PATH</code>中，你需要执行将其可执行文件移动到<code>$GOBIN</code>下</p>
<pre tabindex="0"><code>mv $GOPATH/bin/swag /usr/local/go/bin
</code></pre><h3 id="验证是否安装成功">验证是否安装成功</h3>
<p>检查 $GOBIN 下是否有 swag 文件，如下：</p>
<pre tabindex="0"><code>$ swag -v
swag version v1.6.5
</code></pre><h2 id="安装-gin-swagger">安装 gin-swagger</h2>
<pre tabindex="0"><code>$ go get -u github.com/swaggo/gin-swagger@v1.2.0 
$ go get -u github.com/swaggo/files
$ go get -u github.com/alecthomas/template
</code></pre><p>注：若无科学上网，请务必配置 Go modules proxy。</p>
<h2 id="初始化">初始化</h2>
<h3 id="编写-api-注释">编写 API 注释</h3>
<p><code>Swagger</code> 中需要将相应的注释或注解编写到方法上，再利用生成器自动生成说明文件</p>
<p><code>gin-swagger</code> 给出的范例：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#75715e">// @Summary Add a new pet to the store
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Description get string by ID
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Accept  json
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Produce  json
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param   some_id     path    int     true        &#34;Some ID&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Success 200 {string} string	&#34;ok&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Failure 400 {object} web.APIError &#34;We need ID!!&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Failure 404 {object} web.APIError &#34;Can not find ID&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Router /testapi/get-string-by-int/{some_id} [get]
</span></span></span></code></pre></div><p>我们可以参照 <code>Swagger</code> 的注解规范和范例去编写</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#75715e">// @Summary 新增文章标签
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Produce  json
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param name query string true &#34;Name&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param state query int false &#34;State&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param created_by query int false &#34;CreatedBy&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Success 200 {string} json &#34;{&#34;code&#34;:200,&#34;data&#34;:{},&#34;msg&#34;:&#34;ok&#34;}&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Router /api/v1/tags [post]
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">AddTag</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#75715e">// @Summary 修改文章标签
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Produce  json
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param id path int true &#34;ID&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param name query string true &#34;ID&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param state query int false &#34;State&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Param modified_by query string true &#34;ModifiedBy&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Success 200 {string} json &#34;{&#34;code&#34;:200,&#34;data&#34;:{},&#34;msg&#34;:&#34;ok&#34;}&#34;
</span></span></span><span style="display:flex;"><span><span style="color:#75715e">// @Router /api/v1/tags/{id} [put]
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">EditTag</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
</span></span></code></pre></div><p>参考的注解请参见 <a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a>。以确保获取最新的 swag 语法</p>
<h3 id="路由">路由</h3>
<p>在完成了注解的编写后，我们需要针对 swagger 新增初始化动作和对应的路由规则，才可以使用。打开 routers/router.go 文件，新增内容如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">routers</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">_</span> <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/docs&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// InitRouter initialize routing information
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">InitRouter</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Engine</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/swagger/*any&#34;</span>, <span style="color:#a6e22e">ginSwagger</span>.<span style="color:#a6e22e">WrapHandler</span>(<span style="color:#a6e22e">swaggerFiles</span>.<span style="color:#a6e22e">Handler</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">apiv1</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Group</span>(<span style="color:#e6db74">&#34;/api/v1&#34;</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">apiv1</span>.<span style="color:#a6e22e">Use</span>(<span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">JWT</span>())
</span></span><span style="display:flex;"><span>	{
</span></span><span style="display:flex;"><span>		<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="生成">生成</h3>
<p>我们进入到<code>gin-blog</code>的项目根目录中，执行初始化命令</p>
<pre tabindex="0"><code>[$ gin-blog]# swag init
2018/03/13 23:32:10 Generate swagger docs....
2018/03/13 23:32:10 Generate general API Info
2018/03/13 23:32:10 create docs.go at  docs/docs.go
</code></pre><p>完毕后会在项目根目录下生成<code>docs</code></p>
<pre tabindex="0"><code>docs/
├── docs.go
└── swagger
    ├── swagger.json
    └── swagger.yaml
</code></pre><p>我们可以检查 <code>docs.go</code> 文件中的 <code>doc</code> 变量，详细记载中我们文件中所编写的注解和说明
<img src="https://image.eddycjy.com/37ae10e1714c63899a55d49c19af0860.png" alt="image"></p>
<h3 id="验证">验证</h3>
<p>大功告成，访问一下 <code>http://127.0.0.1:8000/swagger/index.html</code>， 查看 <code>API</code> 文档生成是否正确</p>
<p><img src="https://image.eddycjy.com/703b677c6756129c33b5308c1655a35c.png" alt="image"></p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 01 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-15-reload-http/">「连载七」优雅的重启服务</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-15-log/">「连载六」编写一个简单的文件日志</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-14-jwt/">「连载五」使用 JWT 进行身份校验</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-13-api-03/">「连载四」Gin搭建Blog API&#39;s （三）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-02-12-api-02/">「连载三」Gin搭建Blog API&#39;s （二）</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/gin/2018-03-15-reload-http/"
                                                    rel="prev">「连载七」优雅的重启服务</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/crawler/2018-03-21-douban-top250/">爬取豆瓣电影 Top250</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>